<template>
  <div class="bg-white m-4 mr-0 overflow-hidden">
    <a-spin :spinning="loading">
     <!--设备类型树-->
     <BasicTree v-if="!treeReloading" :treeData="treeData" title="设备类型" ref="treeRef" toolbar showLine  :fieldNames="fieldNames" :checkable="false" @select="onSelect" />
    </a-spin>
  </div>
</template>

<script lang="ts" setup>
  import { inject, nextTick, ref, unref } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicTree, TreeActionType } from '/@/components/Tree';
  import { list as deviceTypeList } from '../../deviceType/deviceType.api';

  const prefixCls = inject('prefixCls');
  const emit = defineEmits(['select']);
  const { createMessage } = useMessage();
  // 树对象
  const treeRef = ref<Nullable<TreeActionType>>(null);
  let loading = ref<boolean>(false);
  // 树列表数据
  let treeData = ref<any[]>([]);
  // 树组件重新加载
  let treeReloading = ref<boolean>(false);
  // 当前选中的项
  const selectedKeys = ref<any[]>([]);
  // 树与数据字段映射
  const fieldNames = {title: 'name',key: 'id'};

  function getTree() {
    const tree = unref(treeRef);
    if (!tree) {
      throw new Error('tree is null!');
    }
    return tree;
  }

  // 加载设备类型信息
  function loadTreeData() {
    loading.value = true;
    treeData.value = [];
    deviceTypeList()
      .then((res) => {
        if (res.success) {
          if (res.data && Array.isArray(res.data)) {
            treeData.value = res.data;
            expandAll(true);
          }
        } else {
          createMessage.warning(res.msg);
        }
      })
      .finally(() => (loading.value = false));
  }

  loadTreeData();

  // 展开全部|折叠全部
  async function expandAll(checkAll: boolean) {
    await nextTick(); //防止无法默认展开数据
    getTree().expandAll(checkAll);
  }

  // 树选择事件
  function onSelect(selKeys, event) {
    if (selKeys.length > 0 && selectedKeys.value[0] !== selKeys[0]) {
      setSelectedKey(selKeys[0], event.selectedNodes[0]);
    } else {
      // 这样可以防止用户取消选择
      setSelectedKey(selectedKeys.value[0]);
    }
  }

  /**
   * 设置当前选中的行
   */
  function setSelectedKey(key: string, data?: object) {
    if (data) {
      emit('select', data);
    }
  }
</script>
